using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
// --- Copyright (c) notice NevoWeb ---
//  Copyright (c) 2008 SARL NevoWeb.  www.nevoweb.com. BSD License.
// Author: D.C.Lee
// ------------------------------------------------------------------------
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
// ------------------------------------------------------------------------
// This copyright notice may NOT be removed, obscured or modified without written consent from the author.
// --- End copyright notice --- 


using System.Reflection;
using DotNetNuke.Services.Scheduling;
using NEvoWeb.Modules.NB_Store.SharedFunctions;
using System.IO;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities;
using DotNetNuke.UI.Skins;
using DotNetNuke.Entities.Tabs;

namespace NEvoWeb.Modules.NB_Store
{

    public class CleanUpCarts : DotNetNuke.Services.Scheduling.SchedulerClient
    {

        public CleanUpCarts(DotNetNuke.Services.Scheduling.ScheduleHistoryItem objScheduleHistoryItem)
            : base()
        {
            this.ScheduleHistoryItem = objScheduleHistoryItem;
        }

        public override void DoWork()
        {

            try
            {
                //notification that the event is progressing
                this.Progressing();
                //OPTIONAL

                CleanUpCarts();

                //update the result to success since no exception was thrown
                this.ScheduleHistoryItem.Succeeded = true;
                this.ScheduleHistoryItem.AddLogNote("Store Clean Up Carts Completed.");

            }
            catch (Exception exc)
            {
                this.ScheduleHistoryItem.Succeeded = false;
                this.ScheduleHistoryItem.AddLogNote("Store Clean Up Carts failed." + exc.ToString());
                this.ScheduleHistoryItem.Succeeded = false;

                //notification that we have errored
                this.Errored(exc);

                //log the exception
                LogException(exc);
            }
        }

        private void CleanUpCarts()
		{
			CartController objCtrl = new CartController();
			int OrderMins = 2880;
			int CartMins = 10080;
			SettingsController objSCtrl = new SettingsController();
			NB_Store_SettingsInfo objSInfo = default(NB_Store_SettingsInfo);
			DotNetNuke.Entities.Portals.PortalController objPC = new DotNetNuke.Entities.Portals.PortalController();
			ArrayList aryList = null;
			DotNetNuke.Entities.Portals.PortalInfo objPInfo = default(DotNetNuke.Entities.Portals.PortalInfo);

			aryList = objPC.GetPortals();
			foreach ( objPInfo in aryList) {
				// portal may not have a store.
				if (!string.IsNullOrEmpty(GetStoreSetting(objPInfo.PortalID, "version", "None"))) {

					objSInfo = objSCtrl.GetSetting(objPInfo.PortalID, "purgecartmins", GetCurrentCulture);
					if ((objSInfo != null)) {
						CartMins = Convert.ToInt32(objSInfo.SettingValue);
					}

					objSInfo = objSCtrl.GetSetting(objPInfo.PortalID, "purgeordermins", GetCurrentCulture);
					if ((objSInfo != null)) {
						OrderMins = Convert.ToInt32(objSInfo.SettingValue);
					}

					objCtrl.DeleteOldCarts(objPInfo.PortalID, CartMins, OrderMins);

				}
			}

		}

    }


    public class StoreOrderReport : DotNetNuke.Services.Scheduling.SchedulerClient
    {

        public StoreOrderReport(DotNetNuke.Services.Scheduling.ScheduleHistoryItem objScheduleHistoryItem)
            : base()
        {
            this.ScheduleHistoryItem = objScheduleHistoryItem;
        }

        public override void DoWork()
        {

            try
            {
                //notification that the event is progressing
                this.Progressing();
                //OPTIONAL

                DoReport();

                //update the result to success since no exception was thrown
                this.ScheduleHistoryItem.Succeeded = true;
                this.ScheduleHistoryItem.AddLogNote("Store Reports Completed.");

            }
            catch (Exception exc)
            {
                this.ScheduleHistoryItem.Succeeded = false;
                this.ScheduleHistoryItem.AddLogNote("Store Reports failed." + exc.ToString());
                this.ScheduleHistoryItem.Succeeded = false;

                //notification that we have errored
                this.Errored(exc);

                //log the exception
                LogException(exc);
            }
        }


        private void DoReport()
		{
			SettingsController objSCtrl = new SettingsController();
			DotNetNuke.Entities.Portals.PortalController objPC = new DotNetNuke.Entities.Portals.PortalController();
			ArrayList aryList = null;
			DotNetNuke.Entities.Portals.PortalInfo objPInfo = default(DotNetNuke.Entities.Portals.PortalInfo);
			NB_Store_SettingsInfo objSInfoXSL = default(NB_Store_SettingsInfo);
			NB_Store_SettingsInfo objSInfo = default(NB_Store_SettingsInfo);
			string strReport = "";
			string SubjectText = "Orders Report";
			string strXSLFilePath = "";
			string LastRunDay = null;

			aryList = objPC.GetPortals();
			foreach ( objPInfo in aryList) {
				// portal may not have a store.
				if (!string.IsNullOrEmpty(GetStoreSetting(objPInfo.PortalID, "version", "None"))) {
					LastRunDay = GetStoreSetting(objPInfo.PortalID, "orderreport.lastday", "None");

					if (LastRunDay != DateAndTime.Day(DateAndTime.Today).ToString()) {
						//clean up reports
						strReport = GetReportXML(objPInfo.PortalID, GetCurrentCulture);
						objSInfoXSL = objSCtrl.GetSetting(objPInfo.PortalID, "ordersreport.xsl", GetMerchantCulture(objPInfo.PortalID));
						if ((objSInfoXSL != null)) {
							strXSLFilePath = System.Web.Hosting.HostingEnvironment.MapPath(objSInfoXSL.SettingValue);
							if (File.Exists(strXSLFilePath)) {
								strReport = XSLTrans(strReport, strXSLFilePath);
							} else {
								strReport = "ERROR Producing Orders Report. Unable to find xsl required. (" + objSInfoXSL.SettingValue + ")";
							}
						} else {
							strReport = "ERROR Producing Orders Report. Unable to find setting 'ordersreport.xsl'.";
						}

						objSInfo = objSCtrl.GetSetting(objPInfo.PortalID, "ordersreport.subject", GetMerchantCulture(objPInfo.PortalID));
						if ((objSInfo != null)) {
							SubjectText = System.Web.HttpUtility.HtmlDecode(objSInfo.SettingValue);
						}
						//send email
						if (!string.IsNullOrEmpty(GetStoreEmail(objPInfo.PortalID))) {
							DotNetNuke.Services.Mail.Mail.SendMail(GetStoreEmail(objPInfo.PortalID), GetMerchantEmail(objPInfo.PortalID), "", SubjectText, strReport, "", "HTML", "", "", "",
							"");
						}
						SetStoreSetting(objPInfo.PortalID, "orderreport.lastday", DateAndTime.Day(DateAndTime.Today).ToString(), "None", true);
					}
				}
			}



		}

        private string GetReportXML(int PortalID, string Lang)
		{
			OrderController objOCtrl = new OrderController();
			NB_Store_OrderStatusInfo objSTAInfo = default(NB_Store_OrderStatusInfo);
			ArrayList aryList = null;
			dynamic strXML = "<root>";

			aryList = objOCtrl.GetOrderStatusList(Lang);
			if (aryList.Count == 0) {
				//get default orderstatus
				aryList = objOCtrl.GetOrderStatusList("XX");
			}

			foreach ( objSTAInfo in aryList) {
				if (objSTAInfo.OrderStatusID != 70) {
					strXML += getOrderXML(PortalID, objSTAInfo.OrderStatusID);
				}
			}
			strXML += "</root>";
			return strXML;
		}

        private string getOrderXML(int PortalID, int OrderStatus)
		{
			string strXML = "";
			OrderController objCtrl = new OrderController();
			NB_Store_OrdersInfo objOInfo = default(NB_Store_OrdersInfo);
			ArrayList aryList = null;

			aryList = objCtrl.GetOrderList(PortalID, -1, DateAndTime.DateAdd(DateInterval.Year, -2, DateAndTime.Today), DateAndTime.Today, OrderStatus, "");

			if (aryList.Count == 0) {
				strXML += "";
			} else {
				foreach ( objOInfo in aryList) {
					strXML += DotNetNuke.Common.Utilities.XmlUtils.Serialize(objOInfo);
				}
			}

			return strXML;
		}


    }


    public class CreateSalePrices : DotNetNuke.Services.Scheduling.SchedulerClient
    {

        public CreateSalePrices(DotNetNuke.Services.Scheduling.ScheduleHistoryItem objScheduleHistoryItem)
            : base()
        {
            this.ScheduleHistoryItem = objScheduleHistoryItem;
        }

        public override void DoWork()
        {

            try
            {
                //notification that the event is progressing
                this.Progressing();
                //OPTIONAL

                DoSalePrices();

                //update the result to success since no exception was thrown
                this.ScheduleHistoryItem.Succeeded = true;
                this.ScheduleHistoryItem.AddLogNote("Sale Prices Calculation Completed.");

            }
            catch (Exception exc)
            {
                this.ScheduleHistoryItem.Succeeded = false;
                this.ScheduleHistoryItem.AddLogNote("Sale Prices Calculation  failed." + exc.ToString());
                this.ScheduleHistoryItem.Succeeded = false;

                //notification that we have errored
                this.Errored(exc);

                //log the exception
                LogException(exc);
            }
        }

        private void DoSalePrices()
		{
			DotNetNuke.Entities.Portals.PortalController objPC = new DotNetNuke.Entities.Portals.PortalController();
			ArrayList aryList = null;
			DotNetNuke.Entities.Portals.PortalInfo objPInfo = default(DotNetNuke.Entities.Portals.PortalInfo);
			string LastRunDay = null;
			PromoController objPromoCtrl = new PromoController();

			aryList = objPC.GetPortals();
			foreach ( objPInfo in aryList) {
				// portal may not have a store.
				if (!string.IsNullOrEmpty(GetStoreSetting(objPInfo.PortalID, "version", "None"))) {
					LastRunDay = GetStoreSetting(objPInfo.PortalID, "salerates.lastday", "None");
					if (LastRunDay != DateAndTime.Day(DateAndTime.Today).ToString()) {
						objPromoCtrl.createSalePriceTable(objPInfo.PortalID);
						SetStoreSetting(objPInfo.PortalID, "salerates.lastday", DateAndTime.Day(DateAndTime.Today).ToString(), "None", true);
					}
				}
			}

		}

    }

    public class SchedulerReport : DotNetNuke.Services.Scheduling.SchedulerClient
    {

        public SchedulerReport(DotNetNuke.Services.Scheduling.ScheduleHistoryItem objScheduleHistoryItem)
            : base()
        {
            this.ScheduleHistoryItem = objScheduleHistoryItem;
        }

        public override void DoWork()
        {

            try
            {
                //notification that the event is progressing
                this.Progressing();
                //OPTIONAL

                DoReport();

                //update the result to success since no exception was thrown
                this.ScheduleHistoryItem.Succeeded = true;
                this.ScheduleHistoryItem.AddLogNote("Store Reports Completed.");

            }
            catch (Exception exc)
            {
                this.ScheduleHistoryItem.Succeeded = false;
                this.ScheduleHistoryItem.AddLogNote("Store Reports failed." + exc.ToString());
                this.ScheduleHistoryItem.Succeeded = false;

                //notification that we have errored
                this.Errored(exc);

                //log the exception
                LogException(exc);
            }
        }


        private void DoReport()
		{
			DotNetNuke.Entities.Portals.PortalController objPC = new DotNetNuke.Entities.Portals.PortalController();
			ArrayList aryList = null;
			DotNetNuke.Entities.Portals.PortalInfo objPInfo = default(DotNetNuke.Entities.Portals.PortalInfo);
			string strReport = "";
			string strXSLFilePath = "";
			SQLReportController objRCtrl = new SQLReportController();
			NB_Store_SQLReportInfo objRInfo = default(NB_Store_SQLReportInfo);
			ArrayList aryRepList = null;

			aryList = objPC.GetPortals();
			foreach ( objPInfo in aryList) {
				// portal may not have a store.
				if (!string.IsNullOrEmpty(GetStoreSetting(objPInfo.PortalID, "version", "None"))) {

					aryRepList = objRCtrl.GetSQLAdminReportList(objPInfo.PortalID, true, "");

					foreach ( objRInfo in aryRepList) {
						if (objRInfo.SchedulerFlag) {

							if (DateAndTime.Now > calcNextRunTime(objRInfo)) {
								RunReport(objPInfo, objRInfo);

								objRInfo.LastRunTime = DateAndTime.Now;
								objRCtrl.UpdateObjSQLReport(objRInfo);
							}
						}
					}

				}
			}
		}


        private void RunReport(DotNetNuke.Entities.Portals.PortalInfo objPInfo, NB_Store_SQLReportInfo objRinfo)
        {
            SQLReportController objRCtrl = new SQLReportController();


            if ((objRinfo != null))
            {
                objRinfo.SQL = objRCtrl.insertParams(objRinfo.ReportID, -1, objPInfo.PortalID, null, objRinfo.SQL, GetCurrentCulture);
                string strXSLOut = "";
                System.Web.UI.WebControls.DataGrid dgResults = new System.Web.UI.WebControls.DataGrid();
                string dataGridHTML = "";

                dataGridHTML = objRCtrl.GetReportOutput(objRinfo);

                if (objRinfo.EmailResults & !string.IsNullOrEmpty(dataGridHTML) & !string.IsNullOrEmpty(objRinfo.EmailFrom) & !string.IsNullOrEmpty(objRinfo.EmailTo))
                {
                    dataGridHTML = objRCtrl.AddStoreCSSforEmailHTML(dataGridHTML);
                    dataGridHTML = objRinfo.ReportTitle + "<br/>" + dataGridHTML;
                    DotNetNuke.Services.Mail.Mail.SendMail(objRinfo.EmailFrom, objRinfo.EmailTo, "", objRinfo.ReportName, dataGridHTML, "", "HTML", "", "", "",
                    "");
                }
            }

        }


        private DateTime calcNextRunTime(NB_Store_SQLReportInfo objRinfo)
        {
            DateTime NextRunTime = default(DateTime);

            //if re-run time is over a day then make sure the start time is re-set to the hour required.
            if (objRinfo.SchReRunMins >= 1440)
            {
                objRinfo.LastRunTime = Convert.ToDateTime(objRinfo.LastRunTime.ToShortDateString + " " + objRinfo.SchStartHour + ":" + objRinfo.SchStartMins + ":00");
            }

            if (Information.IsNumeric(objRinfo.SchReRunMins))
            {
                NextRunTime = DateAndTime.DateAdd(DateInterval.Minute, Convert.ToInt32(objRinfo.SchReRunMins), objRinfo.LastRunTime);
            }
            return NextRunTime;
        }

    }

    public class StoreStatistics : DotNetNuke.Services.Scheduling.SchedulerClient
    {

        public StoreStatistics(DotNetNuke.Services.Scheduling.ScheduleHistoryItem objScheduleHistoryItem)
            : base()
        {
            this.ScheduleHistoryItem = objScheduleHistoryItem;
        }

        public override void DoWork()
        {

            try
            {
                //notification that the event is progressing
                this.Progressing();
                //OPTIONAL

                DoReport();

                //update the result to success since no exception was thrown
                this.ScheduleHistoryItem.Succeeded = true;
                this.ScheduleHistoryItem.AddLogNote("Store Statistics Completed.");

            }
            catch (Exception exc)
            {
                this.ScheduleHistoryItem.Succeeded = false;
                this.ScheduleHistoryItem.AddLogNote("Store Statistics failed." + exc.ToString());
                this.ScheduleHistoryItem.Succeeded = false;

                //notification that we have errored
                this.Errored(exc);

                //log the exception
                LogException(exc);
            }
        }


        private void DoReport()
		{
			DotNetNuke.Entities.Portals.PortalController objPC = new DotNetNuke.Entities.Portals.PortalController();
			ArrayList aryList = null;
			DotNetNuke.Entities.Portals.PortalInfo objPInfo = default(DotNetNuke.Entities.Portals.PortalInfo);
			string LastRunDay = null;

			aryList = objPC.GetPortals();
			foreach ( objPInfo in aryList) {
				// portal may not have a store.
				if (!string.IsNullOrEmpty(GetStoreSetting(objPInfo.PortalID, "version", "None"))) {
					LastRunDay = GetStoreSetting(objPInfo.PortalID, "storestatistics.lastday", "None");

					if (LastRunDay != DateAndTime.Day(DateAndTime.Today).ToString()) {
						StatsController objSCtrl = new StatsController();
						System.DateTime PurgeDate = default(System.DateTime);
						string PurgeDays = GetStoreSetting(objPInfo.PortalID, "searchwordpurge.days");
						if (Information.IsNumeric(PurgeDays)) {
							PurgeDate = DateAndTime.DateAdd(DateInterval.Day, Convert.ToInt32(PurgeDays) * -1, DateAndTime.Now);
						} else {
							PurgeDate = DateAndTime.DateAdd(DateInterval.Day, -60, DateAndTime.Now);
						}

						objSCtrl.PurgeSearchWordHits(objPInfo.PortalID, PurgeDate);

						objSCtrl.ProcessSearchWordHits(objPInfo.PortalID);

						SetStoreSetting(objPInfo.PortalID, "storestatistics.lastday", DateAndTime.Day(DateAndTime.Today).ToString(), "None", true);
					}
				}
			}



		}



    }


    public class PurgeStoreFiles : DotNetNuke.Services.Scheduling.SchedulerClient
    {

        public PurgeStoreFiles(DotNetNuke.Services.Scheduling.ScheduleHistoryItem objScheduleHistoryItem)
            : base()
        {
            this.ScheduleHistoryItem = objScheduleHistoryItem;
        }

        public override void DoWork()
        {

            try
            {
                //notification that the event is progressing
                this.Progressing();
                //OPTIONAL

                PurgeStore();

                //update the result to success since no exception was thrown
                this.ScheduleHistoryItem.Succeeded = true;
                this.ScheduleHistoryItem.AddLogNote("Purge Store Files Completed.");

            }
            catch (Exception exc)
            {
                this.ScheduleHistoryItem.Succeeded = false;
                this.ScheduleHistoryItem.AddLogNote("Purge Store Files failed." + exc.ToString());
                this.ScheduleHistoryItem.Succeeded = false;

                //notification that we have errored
                this.Errored(exc);

                //log the exception
                LogException(exc);
            }
        }

        private void PurgeStore()
		{
			DotNetNuke.Entities.Portals.PortalController objPC = new DotNetNuke.Entities.Portals.PortalController();
			ArrayList aryList = null;
			DotNetNuke.Entities.Portals.PortalInfo objPInfo = default(DotNetNuke.Entities.Portals.PortalInfo);
			PromoController objPromoCtrl = new PromoController();

			aryList = objPC.GetPortals();
			foreach ( objPInfo in aryList) {
				// portal may not have a store.
				if (!string.IsNullOrEmpty(GetStoreSetting(objPInfo.PortalID, "version", "None"))) {

					Portals.PortalSettings PortalSettings = new Portals.PortalSettings(objPInfo.PortalID);

					PurgeLogFiles(PortalSettings);

					PurgeAllFiles(PortalSettings);

				}
			}

		}

    }

}
